const express = require("express");
const uploads = express.Router();
const multer = require("multer");

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "static/uploads/");
    },
    filename: function (req, file, cb) {
        const ext = file.originalname.split(".").pop();
        cb(null, Date.now() + "." + ext);
    },
});

const upload = multer({
    storage,
    limits: {
        fileSize: 1024 * 1024 * 2,
    },
    fileFilter: function (req, file, cb) {
        const ext = file.originalname.split(".").pop();
        if (ext !== "jpg" && ext !== "png") {
            return cb(new Error("文件格式错误"));
        }
        cb(null, true);
    },
});

uploads.post("/", upload.single("avatar"), (req, res) => {
    const { username, password } = req.body;
    const avatar = req.file ? `uploads/${req.file.filename}` : "";
    res.send({
        code: 200,
        msg: "提交成功",
        data: {
            username,
            avatar,
        },
    });
});

module.exports = uploads;
